﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using Microsoft.WindowsMobile.Samples.Location;

namespace foursquare.Location
{
    /// <summary>
    /// Location Provider to get GPS data from a GPS enabled device or GPS peripheral
    /// </summary>
    internal class GpsLocationProvider : ILocationProvider
    {
        private Gps _gps = new Gps();
        private GpsPosition _currentPosition;

        ~GpsLocationProvider()
        {
            Stop();
        }

        #region ILocationProvider Members

        /// <summary>
        /// Starts polling for GPS changes.
        /// </summary>
        public void Start()
        {
            _gps.LocationChanged += new Microsoft.WindowsMobile.Samples.Location.LocationChangedEventHandler(_gps_LocationChanged);

            if (!_gps.Opened)
            {
                _gps.Open();
            }
        }
        /// <summary>
        /// Stops polling for GPS changes.
        /// </summary>
        public void Stop()
        {
            // Unsubscribe from event so the gps thread can obtain a lock for closing the connection
            _gps.LocationChanged -= new Microsoft.WindowsMobile.Samples.Location.LocationChangedEventHandler(_gps_LocationChanged);

            if (_gps.Opened)
            {
                _gps.Close();
            }
        }
        /// <summary>
        /// Gets the current location.
        /// </summary>
        /// <value>The current location.</value>
        public GeoLocation CurrentLocation
        {
            get
            {
                if (_currentPosition != null)
                {
                    return new GeoLocation() { Latitude = _currentPosition.Latitude, Longitude = _currentPosition.Longitude };
                }
                else
                {
                    return GeoLocation.Empty;
                }
            }
        }

        #endregion
        
        /// <summary>
        /// Handles the LocationChanged event of the _gps control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="args">The <see cref="Microsoft.WindowsMobile.Samples.Location.LocationChangedEventArgs"/> instance containing the event data.</param>
        private void _gps_LocationChanged(object sender, Microsoft.WindowsMobile.Samples.Location.LocationChangedEventArgs args)
        {
            _currentPosition = args.Position;
        }
    }
}
